<?php
declare(strict_types=1);
/**
 * @project: 兔兔找图微信小程序
 * @author: kert
 * @date: 2023/5/16
 * @link: https://www.qqdeveloper.com/
 * @site: 微信搜索-兔兔找图
 */

namespace App\Library\Ai\BaiDu;

use App\Constant\CacheKey;
use App\Exceptions\AiException;
use App\Library\RedisClient;

class ApiBase
{
    protected $accessToken = "";

    public function __construct()
    {
        $this->accessToken = $this->getAccessToken();
    }

    protected function requestPost($url = '', $param = ''): array
    {
        if (empty($url) || empty($param)) {
            return [];
        }
        $postUrl = $url;
        $curlPost = $param;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($curl);
        curl_close($curl);
        $result = json_decode($data, true);
        if (isset($result["error_code"])) {
            throw new AiException($result["error_msg"]);
        }
        return json_decode($data, true);
    }

    private function getAccessToken(): string
    {
        $accessToken = RedisClient::client()->hMGet(CacheKey::$baiduAiAccessToken, [
            "create_timestamp",
            "access_token",
            "expires_in"
        ]);
        if (empty($accessToken) || $accessToken["create_timestamp"] + 86400 * 25 < time()) {
            $curl = curl_init();
            $appId = env("BAIDU_AI_KEY");
            $appSecret = env("BAIDU_AI_SECRET");
            curl_setopt_array($curl, array(
                CURLOPT_URL            => "https://aip.baidubce.com/oauth/2.0/token?client_id={$appId}&client_secret={$appSecret}&grant_type=client_credentials",
                CURLOPT_TIMEOUT        => 30,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CUSTOMREQUEST  => 'POST',
                CURLOPT_HTTPHEADER     => array(
                    'Content-Type: application/json',
                    'Accept: application/json'
                ),
            ));
            $response = curl_exec($curl);
            curl_close($curl);
            $responseArray = json_decode($response, true);
            if (isset($responseArray["error"])) {
                return "";
            }
            RedisClient::client()->hMSet(CacheKey::$baiduAiAccessToken, [
                "refresh_token"    => $responseArray["refresh_token"],
                "expires_in"       => $responseArray["expires_in"],
                "session_key"      => $responseArray["session_key"],
                "access_token"     => $responseArray["access_token"],
                "session_secret"   => $responseArray["session_secret"],
                "create_timestamp" => time(),
            ]);
            $accessToken = [
                "access_token" => $responseArray["access_token"],
            ];
        }
        return $accessToken["access_token"];
    }
}
